#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstring>
#include <string>

#include "Inet_Addr.hpp"

void Usage(char *argv[])
{
    printf("%s\n\t[IP] [Port]", argv[0]);
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv);
        exit(1);
    }

    uint16_t port = htons(std::stoi(argv[2]));
    uint32_t ip = inet_addr(argv[1]);

    struct sockaddr_in serverAddr;
    bzero(&serverAddr, sizeof(serverAddr));
    serverAddr.sin_addr.s_addr = ip;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = port;

    // 创建socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket() error" << std::endl;
        exit(1);
    }

    // 申请连接connect
    int ret = connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
    if (ret < 0)
    {
        std::cerr << "connect() error" << std::endl;
        exit(2);
    }

    // 开始通信
    while (true)
    {
        std::string clientMassage;
        std::cout << "send massage# ";
        std::getline(std::cin, clientMassage);

        // 发消息
        int sn = send(sockfd, clientMassage.c_str(), clientMassage.size(), 0);
        if (sn < 0)
        {
            std::cerr << "connect() error" << std::endl;
            exit(3);
        }   

        char serverMassage[1024]{0};
        //收消息
        int rn = recv(sockfd, serverMassage, sizeof(serverMassage) - 1, 0);
        if (rn < 0)
        {
            std::cerr << "recv() error" << std::endl;
            exit(4);
        }
        std::cout << "server echo: " << serverMassage << std::endl;

    }

    return 0;
}